<%--suppress ALL --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ include file="../common/header.jsp" %>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=${AK}"></script>
<style>
    #mapContainer {
        height: 600px
    }

    <%--百度地图取消显示logo--%>
    .BMap_cpyCtrl {
        display: none;
    }

    .anchorBL {
        display: none;
    }

    #files {
        text-align: center;
        margin-top: 13px
    }

    .layui-upload-list {
        min-width: 500px;
        margin-left: 5px
    }
</style>
<div id="saper-container">
    <div id="saper-hd"></div>
    <div id="saper-bd">
        <div class="subfiled clearfix">
            <h2>${titleName}</h2>
        </div>
        <div class="subfiled-content">
            <form class="layui-row saper-form">
                <div class="layui-col-md6 layui-col-sm12">
                    <div class="kv-item clearfix">
                        <label>所在省市：</label>
                        <div class="kv-item-content">
                            <input type="text" value="四川省宜宾市" readonly/>
                        </div>
                        <div class="kv-item-tip">默认</div>
                    </div>
                    <div class="kv-item clearfix">
                        <label>所在县：</label>
                        <div class="kv-item-content">
                            <input type="text" value="兴文县" readonly/>
                        </div>
                        <div class="kv-item-tip">默认</div>
                    </div>
                    <div class="kv-item clearfix">
                        <label>
                            <span class="impInfo">*</span>所在乡镇：</label>
                        <div class="kv-item-content">
                            <select name="townId" onchange="select_change(this)">
                                <c:forEach items="${townList}" var="town">
                                    <option value="${town.townId}">${town.townName}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                    <div class="kv-item clearfix">
                        <label>
                            <span class="impInfo">*</span>所在村庄：</label>
                        <div class="kv-item-content">
                            <select name="villageId">
                                <c:forEach items="${villageList}" var="village">
                                    <option value="${village.villageId}">${village.villageName}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                    <div class="kv-item clearfix">
                        <label>
                            <span class="impInfo">*</span>详细地址：</label>
                        <div class="kv-item-content">
                            <input type="text" name="address" placeholder="请输入详细地址" autocomplete="off"/>
                        </div>
                    </div>
                    <div class="kv-item clearfix">
                        <label>
                            <span class="impInfo">*</span>主要对象：</label>
                        <div class="kv-item-content">
                            <select name="mainObject">
                                <c:forEach items="${mainObject}" var="object">
                                    <option value="${object.id}">${object.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                    <div class="kv-item clearfix">
                        <label>
                            <span class="impInfo">*</span>主要内容：</label>
                        <div class="kv-item-content">
                            <select name="mainContent">
                                <c:forEach items="${mainContent}" var="content">
                                    <option value="${content.id}">${content.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                    <div class="kv-item clearfix">
                        <label><span class="impInfo">*</span>gis信息：</label>
                        <div class="kv-item-content">
                            <input name="gis" type="text" placeholder="请点击右侧地图选择位置" autocomplete="off" readonly/>
                        </div>
                        <div class="kv-item-tip">民情日记的gis精准定位</div>
                    </div>
                    <div class="kv-item clearfix">
                        <label><span class="impInfo">*</span>总结：</label>
                        <div class="kv-item-content">
                            <textarea class="layui-textarea layui-hide" name="comment" lay-verify="require"
                                      id="eventContent"></textarea>
                        </div>
                    </div>
                    <div class="kv-item clearfix">
                        <label class="layui-btn layui-btn-xs" onclick="add_copnote_person()"
                               style="margin-top: 13px;text-align: center">走访人员</label>
                        <div class="kv-item-content">
                            <div class="layui-upload-list">
                                <table class="layui-table">
                                    <thead>
                                    <tr>
                                        <th>姓名</th>
                                        <th>成员数</th>
                                        <th>资金收入</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="personList">

                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="kv-item clearfix">
                        <label class="layui-btn layui-btn-xs" id="files">选择附件</label>
                        <div class="kv-item-content">
                            <div class="layui-upload-list">
                                <table class="layui-table">
                                    <thead>
                                    <tr>
                                        <th>文件名</th>
                                        <th>大小</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="fileList"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6 layui-col-sm12" id="mapContainer" style="margin-bottom: 10px"></div>
                <div class="layui-col-md12" style="padding-bottom: 25px">
                    <div class="buttons">
                        <a href="javascript:;" class="sapar-btn sapar-btn-recom">确定</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <div id="saper-ft"></div>
</div>

<%@ include file="../common/footer.jsp" %>

<script type="text/javascript">

    var nowTime = new Date().getTime();
    <%--上访人员列表--%>
    var personList = [];

    <%--更新上访人员--%>
    function add_person(person){
        var len = personList.length;
        person['familyPnum'] = parseInt(person['familyPnum']);
        person['personType'] = parseInt(person['personType']);
        person['economicsIncome'] = parseFloat(person['economicsIncome']);
        personList[len] = person;
        update_person();
    }

    <%--更新人员列表--%>
    function update_person(){
        var p = '';
        for(var i=0,len = personList.length;i<len;i++){
            person = personList[i];
            p += '<tr><td>'+person.name+'</td><td>'+person.familyPnum+'</td><td>'+person.economicsIncome+'</td><td>' +
                '<button type="button" class="layui-btn layui-btn-xs layui-btn-danger" onclick="delete_person('+i+')">删除</button>' +
                '</td></tr>';
        }
        $("#personList").html(p);
    }

    <%--删除上访人员--%>
    function delete_person(index){
        layer.msg("删除成功！");
        personList.splice(index,1);
        update_person();
    }


    <%--下拉框更新--%>
    function select_change(obj) {
        var that = $(obj);
        var select = that[0];
        var select_name = $(select).attr("name");
        if (select_name === "townId")
            $.post("/ajax/grid/getVillage", {
                townId: $(select).val()
            }, function (res) {
                if (res.code === 1) {
                    var data = res.data, len = res.data.length;
                    if (len === 0) {
                        $("select[name=villageId]").html("");
                        $("select[name=villageId]").next().html("没有可以选取的类别");
                    } else {
                        var str = '';
                        for (var i = 0; i < len; i++) {
                            var d = data[i];
                            str += '<option value="' + d['villageId'] + '">' + d['villageName'] + '</option>\n'
                        }
                        $("select[name=villageId]").html(str);
                        $("select[name=villageId]").next().html(data[0]['villageName']);
                    }
                } else
                    console.log("请求失败！");
            });
    }

    <%--新增上访人员--%>
    function add_copnote_person() {
        var data = {};
        var len = ${mainObject.size()};
        data["person"] = [];

        <c:forEach items="${mainObject}" var="object">
        var obj = {'id': "${object.id}", 'name': "${object.name}"};
        data["person"].push(obj);
        </c:forEach>

        var addPerson = layer.open({
            type: 1,
            area: ['686px','500px'],
            title: '新增走访人员',
            content: add_copnote_person_alert(data)
        });
        //初始化时间选择器
        laydate.render({
            elem: '#copnotePersonTime' //指定元素
        });
        //初始化表单
        form.render();
        form.on('submit(copnotePersonForm)', function(data){
            add_person(data.field);
            layer.close(addPerson);
            layer.msg("信息已录入");
            return false;
        });

    }

    <%--初始化文本编辑器--%>
    {
        //配置图片上传接口
        layedit.set({
            uploadImage: {
                url: '/api/spfile/images' //接口url
                , type: 'post' //默认post
            }
        });
        var editIndex = layedit.build('eventContent', {
            height: 200,
            tool: ['strong' //加粗
                , 'italic' //斜体
                , 'underline' //下划线
                , 'del' //删除线
                , '|' //分割线
                , 'left' //左对齐
                , 'center' //居中对齐
                , 'right' //右对齐
                , 'link' //超链接
                , 'unlink' //清除链接
                , 'face' //表情
                , 'image'//插入图片
            ]
        });
    }

    <%--多文件上传--%>
    {
        var fileList = {}, demoListView = $('#fileList')
            , uploadListIns = upload.render({
            elem: '#files'
            ,url:'/api/spfile/upload'  //上传接口
            ,data:{
                tableName: '民情日记上报表',
                index:nowTime
            }
            , accept: 'file'
            , multiple: true
            , size: 200*1024
            , auto: true
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        delete fileList[index];
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    demoListView.append(tr);
                });
            }
            , done: function (res, index, upload) {
                if (res.code === 0) { //上传成功
                    var tr = demoListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    fileList[index] = res.data.src;
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = demoListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });
    }

    <%--创建地图--%>
    {
        var map = new BMap.Map("mapContainer", {
            minZoom: 10
        });         // 创建地图实例
        var point = new BMap.Point(105.2428, 28.31);    // 创建点坐标
        map.centerAndZoom(point, 14);                   // 设置缩放度
        map.enableScrollWheelZoom();                    //启用滚轮放大缩小

        //自动定位
        // var geolocation = new BMap.Geolocation();
        // geolocation.getCurrentPosition(function (r) {
        //     if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        //         map.panTo(r.point);
        //     }
        //     else {
        //         alert('failed' + this.getStatus());
        //     }
        // }, {enableHighAccuracy: true});

        //鼠标获取事件
        map.addEventListener("click", function (e) {
            map.clearOverlays();
            var marker = new BMap.Marker(e.point);      // 创建标注
            map.addOverlay(marker);                     // 将标注添加到地图中
            var gisStr = e.point.lng + "," + e.point.lat;
            $("input[name=gis]").val(gisStr);
        });
    }

    <%--表单提交--%>
    $(".sapar-btn-recom").click(function () {
        var param = {
            categoryId: 6,           //基于gis事件上报
            villageId: parseInt($("select[name=villageId]").val()),
            townId: parseInt($("select[name=townId]").val()),
            mainObjectId: parseInt($("select[name=mainObject]").val()),
            mainContentId: parseInt($("select[name=mainContent]").val()),
            address: $("input[name=address]").val(),
            gis: $("input[name=gis]").val(),
            title: $("input[name=title]").val(),
            comment: layedit.getContent(editIndex),
            personList: personList,
            files: fileList
        };


        if (report_valid(param))

            console.log($("#personList").children());
            if($("#personList").children().length==0){
                layer.alert("走访人员是必填项！")
            }else {
                $.post("/ajax/grid/saveCopnote", {param: JSON.stringify(param), taskId:nowTime}, function (res) {
                    console.log(res);
                    if (res.code === 1) {
                        layer.alert("上报成功，等待指挥中心审核", {icon: 6}, function () {
                            refresh();
                        });
                    }
                });
            }
    });

</script>

